package com.g17.virtualpetbackend.repo;

import com.g17.virtualpetbackend.entity.Paper;
import org.neo4j.driver.internal.value.FloatValue;
import org.neo4j.driver.internal.value.PathValue;
import org.springframework.data.neo4j.repository.Neo4jRepository;
import org.springframework.data.neo4j.repository.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PaperRepository extends Neo4jRepository<Paper, Long> {

    @Query("MATCH (p:Paper) " +
            "WHERE id(p) = $paperId " +
            "RETURN p")
    Paper findPaperById(Long paperId);

    @Query("CREATE (p:Paper) RETURN p")
    Paper createPaper();

    @Query("MATCH (p:Paper), (t:Test) " +
            "WHERE id(p) = $paperId AND id(t) = $questionId " +
            "CREATE path = (p)-[i:INCLUDE]->(t) " +
            "RETURN path")
    List<PathValue> linkPaperAndQuestion(Long paperId, Long questionId);

    @Query("MATCH (p:Paper), (u:user) " +
            "WHERE id(p) = $paperId AND u.username = $username " +
            "MERGE path = (u) - [a:ATTEND {score:0, hasTest:false, time:$time}] -> (p) " +
            "RETURN path")
    List<PathValue> linkPaperAndUser(Long paperId, String username, String time);

    @Query("MATCH (u:user)-[a:ATTEND]->(p:Paper) " +
            "WHERE u.username = $username AND id(p) = $paperId " +
            "DELETE a " +
            "RETURN p")
    Paper unlinkPaperAndUser(Long paperId, String username);

    @Query("MATCH (u:user)-[a:ATTEND]->(p:Paper) " +
            "WHERE u.username = $username " +
            "RETURN p")
    List<Paper> findAllPaperByUsername(String username);

    @Query("MATCH path=(u:user)-[a:ATTEND]->(p:Paper) " +
            "WHERE u.username = $username AND id(p) = $paperId " +
            "RETURN path")
    List<PathValue> findRelationshipByNodes(String username, Long paperId);

    @Query("MATCH (u:user)-[a:ATTEND]->(p:Paper) " +
            "WHERE u.username = $username AND id(p) = $paperId " +
            "SET a.score = $score " +
            "RETURN toFloat(a.score)")
    List<FloatValue> setScore(Long paperId, String username, Float score);

    @Query("MATCH (u:user)-[a:ATTEND]->(p:Paper) " +
            "WHERE u.username = $username AND id(p) = $paperId " +
            "SET a.hasTest = true")
    void setHasTest(Long paperId, String username);
}
